package com.fc.remoting.handler;

import java.util.concurrent.RejectedExecutionException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fc.remoting.client.IRemotingCallBack;
import com.fc.remoting.exception.IRemotingException;
import com.fc.remoting.logger.RemotingLogger;
import com.fc.remoting.message.DefaultRemotingMessage;
import com.fc.remoting.message.RemotingMessage;
import com.fc.remoting.message.RemotingMessageType;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class RemotingClientMessageHandler extends SimpleChannelInboundHandler<RemotingMessage> {
	
	private static final String DEFAULT_ENCODE = "UTF-8";
	
	
	private static IRemotingCallBack<JSON> iRemotingCallBack;
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		ctx.close();
	}
	
	@Override
	protected void messageReceived(ChannelHandlerContext ctx, RemotingMessage msg) throws Exception {
		if (msg == null) {
			return;
		}
		try {
			int msgType = msg.getHeader().getMsgType();
			if (msgType == RemotingMessageType.HEART_BEAT) {
				ctx.channel().writeAndFlush(DefaultRemotingMessage.heartBeatMessage().build());
				return;
			}
			JSONObject message = JSONObject.parseObject(new String(msg.getBody(),DEFAULT_ENCODE));
			iRemotingCallBack.onMessageRecived(message);
		} catch (RejectedExecutionException e) {
			RemotingLogger.getLogger().error(e.getMessage(), msg);
			throw new IRemotingException(e.getMessage(), e);
		} catch (Exception e) {
			RemotingLogger.getLogger().error(e.getMessage(), msg);
			throw new IRemotingException(e.getMessage(), e);
		}
	}
	
	public static <I> void setCallBack(IRemotingCallBack<JSON> callBack){
		iRemotingCallBack = callBack;
	}

}
